﻿using System;
namespace Moonlite.ExtensionApi
{
    public static class ConvertByteAndInt
    {
        private const int Offset = 0x100; // 256
        public static int ConvertByteArrayToInt(byte[] input)
        {
            int output = 0;
            foreach (byte b in input)
            {
                output *= Offset;
                output += b;
            }

            return output;
        }

        public static byte[] ConvertIntToByteArray(int input)
        {
            if (input == 0) return new byte[1];
            byte[] buffer = new byte[8];
            int inputRef = input;
            int index = 0;
            while (inputRef > 0)
            {
                int modRef = inputRef % Offset;
                buffer[index] = (byte)modRef;
                inputRef = (inputRef - modRef) / Offset;
                index++;
            }

            byte[] outputBuffer = new byte[index];
            for (int i = 0; i < index; i++)
            {
                outputBuffer[i] = buffer[(index - i) - 1];
            }

            return outputBuffer;
        }

        public static void ConvertIntToByteArray(uint input, byte[] counter)
        {
            if (input == 0) return;
            uint inputRef = input;
            int index = 0;
            while (inputRef > 0)
            {
                uint modRef = input % Offset;
                counter[3 - index] = (byte)modRef;
                inputRef = (inputRef - modRef) / Offset;
                index++;
            }
        }
    }
}
